package com.example.news;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.news.apapter.NewsAdapter;
import com.example.news.cons.Cons;
import com.example.news.entity.News;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * @author Admin
 */
public class TabNewsFragment extends Fragment {
    public static final String TAG = "MainActivity-LOG-TabNewsFragment";
    public static final String HTTP_URL = "";
    private static final String ARG_PARAM = "title";
    public static final int MESSSAGE_CODE = 100;
    public static final String DATA_DTO = "dataDTO";
    private String title;
    private View view;
    private RecyclerView recycleView;

    private NewsAdapter newsAdapter;
    // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == MESSSAGE_CODE) {
                String responseText = (String) msg.obj;
                News news = new Gson().fromJson(responseText, News.class);
                if (Objects.nonNull(news) && Objects.equals(0, news.getErrorCode())) {
                    // 加载数据
                    if (Objects.nonNull(newsAdapter)) {
                        List<News.ResultDTO.DataDTO> data = news.getResult().getData();
                        newsAdapter.setList(data);
                    }
                } else {
                    Toast.makeText(getActivity(), "load data err ", Toast.LENGTH_SHORT);
                }
            }
        }
    };
    public TabNewsFragment(){

    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    /**
     * @param title
     * @return
     */
    public static TabNewsFragment newInstance(String title) {
        TabNewsFragment fragment = new TabNewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM, title);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView ");
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_tab_news, container, false);
        recycleView = view.findViewById(R.id.recycleView);
        //
        //recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onActivityCreated: ");
        super.onActivityCreated(savedInstanceState);
        // 获取数据
        newsAdapter = new NewsAdapter(getActivity());
        newsAdapter.setOnItemClickListener((dataDTO, position) -> {
            // Fragment里获取上下文用getActivity()
            Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
            // 把整个对像传过去
            // 要传递的对象必须要实现 Serializable
            // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
            intent.putExtra(DATA_DTO, dataDTO);
            startActivity(intent);
        });
        //  获取数据
//        getHttpData();
//        sendMessage
        // 设置数据
        sendMessage(Cons.fakeMsg);
        recycleView.setAdapter(newsAdapter);

    }

    private void getHttpData() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(HTTP_URL)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: ");
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseText = response.body().string();
                Log.d(TAG, "onResponse: " + responseText);
                // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                // 放到异步线程处理
                sendMessage(responseText);
            }
        });

    }

    private void sendMessage(String responseText){
        Message message = new Message();
        message.what = MESSSAGE_CODE;
        message.obj = responseText;
        handler.sendMessage(message);
    }
}